import { User } from '../models/User.js';
import { sendSpugNotification } from '../utils/spugUtils.js';

const userModel = new User();
const verificationCodes = new Map();

export class AuthController {
  // 发送验证码
  async sendSMSCode(req, res) {
    try {
      const { phone, type = 'login' } = req.body;
      
      if (!phone) {
        return res.status(400).json({ error: '手机号不能为空' });
      }

      if (!/^1[3-9]\d{9}$/.test(phone)) {
        return res.status(400).json({ error: '请输入正确的手机号' });
      }

      const users = userModel.findAll();
      const user = users.find(u => u.phone === phone);
      
      if (type === 'login' && !user) {
        return res.status(404).json({ error: '手机号未注册，请先注册' });
      }
      
      if (type === 'register' && user) {
        return res.status(400).json({ error: '手机号已注册' });
      }

      const code = Math.floor(100000 + Math.random() * 900000).toString();
      const expiresAt = Date.now() + 10 * 60 * 1000;

      const codeKey = type === 'register' ? `register_${phone}` : phone;
      verificationCodes.set(codeKey, {
        code,
        expiresAt,
        phone,
        sentAt: new Date().toISOString(),
        type
      });

      console.log(`准备发送${type}验证码到手机: ${phone}, 验证码: ${code}`);

      const sendResult = await sendSpugNotification(phone, code);

      if (sendResult) {
        res.json({
          success: true,
          message: `验证码已发送到您的手机`,
          phone: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
          type
        });
      } else {
        verificationCodes.delete(codeKey);
        res.status(500).json({ error: '验证码发送失败，请稍后重试' });
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      res.status(500).json({ error: '验证码发送失败' });
    }
  }

  // 手机号验证码登录
  async loginWithPhone(req, res) {
    try {
      const { phone, code } = req.body;

      if (!phone || !code) {
        return res.status(400).json({ error: '手机号和验证码为必填字段' });
      }

      const users = userModel.findAll();
      const user = users.find(u => u.phone === phone);

      if (!user) {
        return res.status(401).json({ error: '手机号未注册' });
      }

      const verificationData = verificationCodes.get(phone);
      if (!verificationData) {
        return res.status(400).json({ error: '请先获取验证码' });
      }

      if (verificationData.expiresAt < Date.now()) {
        verificationCodes.delete(phone);
        return res.status(400).json({ error: '验证码已过期，请重新获取' });
      }

      if (verificationData.code !== code) {
        return res.status(400).json({ error: '验证码错误' });
      }

      verificationCodes.delete(phone);
      userModel.updateLastLogin(user.id);

      const { password: _, ...userInfo } = user;
      
      res.json({
        success: true,
        message: '登录成功',
        user: userInfo,
        token: `mock-jwt-token-${user.id}`
      });
    } catch (error) {
      console.error('手机号登录失败:', error);
      res.status(500).json({ error: '登录失败' });
    }
  }

  // 密码登录
  async login(req, res) {
    try {
      const { username, password } = req.body;
      console.log('登录请求:', { username, password });

      if (!username || !password) {
        return res.status(400).json({ error: '用户名和密码为必填字段' });
      }

      const users = userModel.findAll();
      const user = users.find(u => u.username === username && u.password === password);

      if (!user) {
        return res.status(401).json({ error: '用户名或密码错误' });
      }

      userModel.updateLastLogin(user.id);

      const { password: _, ...userInfo } = user;
      
      res.json({
        success: true,
        message: '登录成功',
        user: userInfo,
        token: `mock-jwt-token-${user.id}`
      });
    } catch (error) {
      console.error('登录失败:', error);
      res.status(500).json({ error: '登录失败' });
    }
  }

  // 用户注册
  async register(req, res) {
    try {
      const { phone, code, password, username } = req.body;

      if (!phone || !code || !password) {
        return res.status(400).json({ error: '手机号、验证码和密码为必填字段' });
      }

      if (password.length < 6) {
        return res.status(400).json({ error: '密码长度至少6位' });
      }

      const users = userModel.findAll();
      
      if (users.find(u => u.phone === phone)) {
        return res.status(400).json({ error: '手机号已注册' });
      }

      if (username && users.find(u => u.username === username)) {
        return res.status(400).json({ error: '用户名已存在' });
      }

      const verificationData = verificationCodes.get(`register_${phone}`);
      if (!verificationData) {
        return res.status(400).json({ error: '请先获取验证码' });
      }

      if (verificationData.expiresAt < Date.now()) {
        verificationCodes.delete(`register_${phone}`);
        return res.status(400).json({ error: '验证码已过期，请重新获取' });
      }

      if (verificationData.code !== code) {
        return res.status(400).json({ error: '验证码错误' });
      }

      verificationCodes.delete(`register_${phone}`);

      const newUser = {
        username: username || `user_${phone}`,
        password: password,
        email: `${phone}@school.edu`,
        phone: phone,
        role: 'user',
        avatar: null,
        createdAt: new Date().toISOString(),
        lastLogin: new Date().toISOString()
      };

      const createdUser = userModel.create(newUser);
      
      if (createdUser) {
        console.log('用户注册成功:', { 
          id: createdUser.id, 
          username: createdUser.username, 
          phone: createdUser.phone 
        });
        
        const { password: _, ...userInfo } = createdUser;
        
        res.status(201).json({
          success: true,
          message: '注册成功',
          user: userInfo,
          token: `mock-jwt-token-${createdUser.id}`
        });
      } else {
        res.status(500).json({ error: '注册失败' });
      }
    } catch (error) {
      console.error('用户注册失败:', error);
      res.status(500).json({ error: '注册失败' });
    }
  }
}

// 清理过期验证码的定时任务
setInterval(() => {
  const now = Date.now();
  for (const [username, data] of verificationCodes.entries()) {
    if (data.expiresAt < now) {
      verificationCodes.delete(username);
      console.log(`清理过期验证码: ${username}`);
    }
  }
}, 60 * 1000);